package config

import (
	"io/ioutil"
	"sync"

	"gopkg.in/yaml.v2"
)

type Global struct {
	App App `yaml:app`
}

type App struct {
	Server Server `yaml:server`
}

type Server struct {
	Host string `yaml:"host"`
	Port string `yaml:"port"`
}

var (
	globalconfig *Global
	configMux    sync.RWMutex
)

func GetGlobalConfig() *Global {
	return globalconfig
}

func InitConfigYaml(fliepath string) (err error) {
	var (
		file   []byte
		config Global
	)

	if file, err = ioutil.ReadFile(fliepath); err != nil {
		goto ERR
	}

	if err = yaml.Unmarshal(file, &config); err != nil {
		goto ERR
	}

	configMux.Lock()
	globalconfig = &config
	configMux.Unlock()
	return
ERR:
	return
}
